package com.atguigu.gulimall.seckill.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.entity.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //秒杀系统中只有秒杀请求需要处理登录，其他请求不需要
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/kill", requestURI);

        if (match){
            HttpSession session = request.getSession();
            MemberResponseVo user = (MemberResponseVo) session.getAttribute(AuthConstant.LOGIN_USER);
            if (user != null){
                //放在ThreadLocal中，以后其他线程都可以获取
                loginUser.set(user);

                return true;
            }else {
                session.setAttribute("msg","请先登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }else {
            return true;
        }
    }
}
